package org.jeecg.modules.job.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.job.api.model.UserModel;
import org.jeecg.modules.job.rms.entity.RmsCompany;
import org.jeecg.modules.job.rms.service.IRmsCompanyService;
import org.jeecg.modules.job.ums.entity.UmsMemberRole;
import org.jeecg.modules.job.ums.service.IUmsMemberRoleService;
import org.jeecg.modules.job.wms.entity.WmsResume;
import org.jeecg.modules.job.wms.service.IWmsResumeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 */
@RestController
@RequestMapping("/api/user")
@Api(tags="移动端用户信息")
@Slf4j
public class AppUserController {
	@Autowired
	private ISysBaseAPI sysBaseApi;
	@Resource
	private BaseCommonService baseCommonService;
	@Resource
	private IUmsMemberRoleService memberRoleService;
	@Resource
	private IWmsResumeService wmsResumeService;
	@Resource
	private IRmsCompanyService companyService;

	/**
	 * 根据id/phone/uuid/username等获取
	 *
	 * @return
	 */
	@ApiOperation("根据id等查询用户信息")
	@GetMapping("/getUserInfo")
	public Result<?> getUserInfo(HttpServletRequest request, UserModel userModel) {
		try {
			LoginUser sysUser=null;
			if(StringUtils.isNotBlank(userModel.getId())){
				sysUser = sysBaseApi.getUserById(userModel.getId());
			}else if(StringUtils.isNotBlank(userModel.getPhone())){
				sysUser = sysBaseApi.getUserByName(userModel.getPhone());
			}else if(StringUtils.isNotBlank(userModel.getUuid())){
				sysUser = sysBaseApi.getUserByName(userModel.getUuid());
			}else if(StringUtils.isNotBlank(userModel.getUsername())){
				sysUser = sysBaseApi.getUserByName(userModel.getUsername());
			}else{
				String username = JwtUtil.getUserNameByToken(request);
				log.debug(" ------ 通过令牌获取部分用户信息，当前用户： " + username);
				// 根据用户名查询用户信息
				sysUser = sysBaseApi.getUserByName(username);
			}
			if (sysUser!=null){
				sysUser.setPassword(null);
				//关联企业
//				if (sysUser.getMemberRole()==1){
					UmsMemberRole memberRole=memberRoleService.getMemberRole(sysUser.getId());
					if (oConvertUtils.isNotEmpty(memberRole)){
						RmsCompany company=companyService.getById(memberRole.getCompanyId());
						if (oConvertUtils.isNotEmpty(company)){
							sysUser.setCompany(company.getName());
							sysUser.setCompanyId(company.getId());
							sysUser.setPostName(memberRole.getPostName());
							sysUser.setCompanyAuth(company.getVerifyStatus());
						}
					}
//				}
				//如果是个人，查询简历
				if (sysUser.getMemberRole() == 0) {
					WmsResume resumeResult = wmsResumeService.getOne(new QueryWrapper<>(new WmsResume().setMemberId(sysUser.getId())));
					if (resumeResult != null) {
						sysUser.setIfAddResume(true);
					} else {
						sysUser.setIfAddResume(false);
					}
				}
			}
			return Result.ok(sysUser);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error(500, "查询失败:" + e.getMessage());
		}
	}

	/**
	 * 根据token获取用户信息
	 * @return
	 */
	@ApiOperation("根据token查询用户信息")
	@GetMapping("/getUserInfoByToken")
	public Result<?> getUserInfoByToken(HttpServletRequest request) {
		try {
			LoginUser sysUser;
			String username = JwtUtil.getUserNameByToken(request);
			log.debug(" ------ 通过令牌获取部分用户信息，当前用户： " + username);
			// 根据用户名查询用户信息
			sysUser = sysBaseApi.getUserByName(username);
			sysUser.setPassword(null);
			//关联企业
			UmsMemberRole memberRole=memberRoleService.getMemberRole(sysUser.getId());
			if (oConvertUtils.isNotEmpty(memberRole)){
				RmsCompany company=companyService.getById(memberRole.getCompanyId());
				if (oConvertUtils.isNotEmpty(company)){
					sysUser.setCompany(company.getName());
					sysUser.setCompanyId(company.getId());
					sysUser.setPostName(memberRole.getPostName());
				}
			}
			return Result.ok(sysUser);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error(500, "查询失败:" + e.getMessage());
		}
	}



	/**
	 * 修改用户信息
	 * @param jsonObject
	 * @return
	 */
	@ApiOperation("修改用户信息")
	@PostMapping(value = "/updateUser")
	public Result<LoginUser> appEdit(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
		Result<LoginUser> result = new Result<LoginUser>();
		try {
			String username = JwtUtil.getUserNameByToken(request);
			LoginUser sysUser = sysBaseApi.getUserByName(username);
			baseCommonService.addLog("移动端编辑用户，id： " +jsonObject.getString("id") , CommonConstant.LOG_TYPE_2, 2);
			String realname=jsonObject.getString("realname");
			String avatar=jsonObject.getString("avatar");
			String sex=jsonObject.getString("sex");
			String phone=jsonObject.getString("phone");
			String email=jsonObject.getString("email");
			Date birthday=jsonObject.getDate("birthday");
			String nickname=jsonObject.getString("nickname");
			String province=jsonObject.getString("province");
			String city=jsonObject.getString("city");
			String area=jsonObject.getString("area");
			String sign=jsonObject.getString("sign");
			LoginUser userPhone = sysBaseApi.getUserByName(phone);
			if(sysUser==null) {
				result.error500("未找到对应用户!");
			}else {
				if(userPhone!=null){
					String userPhonename = userPhone.getUsername();
					if(!userPhonename.equals(username)){
						result.error500("手机号已存在!");
						return result;
					}
				}
				if(StringUtils.isNotBlank(realname)){
					sysUser.setRealname(realname);
				}
				if(StringUtils.isNotBlank(nickname)){
					sysUser.setNickname(nickname);
				}
				if(StringUtils.isNotBlank(avatar)){
					sysUser.setAvatar(avatar);
				}
				if(StringUtils.isNotBlank(sex)){
					sysUser.setSex(Integer.parseInt(sex));
				}
				if(StringUtils.isNotBlank(phone)){
					sysUser.setPhone(phone);
				}
				if(StringUtils.isNotBlank(email)){
					sysUser.setEmail(email);
				}
				if(null != birthday){
					sysUser.setBirthday(birthday);
				}
				sysBaseApi.updateUserInfo(sysUser);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("保存失败!");
		}
		return result;
	}

	/**
	 * 角色切换
	 */
	@ApiOperation(value = "角色切换", notes = "角色切换")
	@PostMapping(value = "/switchRole")
	public Result<?> switchRole(@RequestBody JSONObject jsonObject) throws Exception {
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		//切换到用户，查询是否存在简历
		boolean result = false;
		int role=jsonObject.getIntValue("role");
		UmsMemberRole memberRole =memberRoleService.getMemberRole(user.getId());
		if (role == 0) {
			WmsResume resumeResult = wmsResumeService.getOne(new LambdaQueryWrapper<WmsResume>().eq(WmsResume::getMemberId,user.getId()));
			if (resumeResult != null) {
				//直接切换
				result = true;
			} else {
				//简历不存在
				result = false;
			}
		} else if (role == 1) {
			if (oConvertUtils.isNotEmpty(memberRole)) {
				//直接切换
				result = true;
			} else {
				//未绑定公司
				result = false;
			}
		}
		//切换角色
		user.setMemberRole(role);
		sysBaseApi.updateUserInfo(user);
		return Result.ok(result);
	}







}